package zhihui.mobile.ui.shop.order;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zgm.utils.ui.UiHeaderLayout;

import java.util.List;

import zhihui.mobile.R;
import zhihui.mobile.bean.ilpay.PayResult;
import zhihui.mobile.bean.shop.order.ShopOrder;
import zhihui.mobile.bean.wx.WeixinPayInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.manager.pay.PayManager;
import zhihui.mobile.presenter.IPresenter;
import zhihui.mobile.presenter.shop.ShopOrderManagerPresenter;
import zhihui.mobile.ui.BaseActivity;
import zhihui.mobile.ui.utils.UiUtils;

/**
 * Created by 张公铭 on 2017/8/15 0015.
 */
public class ShopOrderManagerActivity extends BaseActivity implements IShopOrderManagerContrat.IShopOrderManagerView
{
    private ShopOrderManagerPresenter managerPresenter = new ShopOrderManagerPresenter();
    private UiHeaderLayout mheader;
    private TextView tv_order_all;
    private TextView tv_order_obligation;
    private TextView tv_order_wait;
    private TextView tv_order_over;
    private TextView tv_order_cancle;
    private ListView lv_content;
    private LinearLayout ll_noram;
    private ShopOrderManagerItemAdapter adapter;

    private int state = 0;
    private Handler mHander;
    private static final int SDK_PAY_FLAG = 1;
    private IWXAPI api;

    @Override
    protected void parseArgumentsFormIntent(Intent argIntent)
    {
        state = argIntent.getIntExtra("orderState", 0);
    }

    @Override
    public void initView()
    {
        api = WXAPIFactory.createWXAPI(this, Config.WX_APP_ID, true);
        api.registerApp(Config.WX_APP_ID);
        PayManager.wx_pay = 0;

        mHander = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                switch (msg.what)
                {
                    case SDK_PAY_FLAG:
                    {
                        PayResult payResult = new PayResult((String) msg.obj);
                        /**
                         * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                         * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                         * docType=1) 建议商户依赖异步通知
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000"))
                        {
                            Toast.makeText(ShopOrderManagerActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        } else
                        {
                            // 判断resultStatus 为非"9000"则代表可能支付失败
                            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000"))
                            {
                                Toast.makeText(ShopOrderManagerActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                            } else
                            {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                Toast.makeText(ShopOrderManagerActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
        };

        mheader = (UiHeaderLayout) findViewById(R.id.shop_order_manager_header);
        mheader.setTitle("我的订单");
        mheader.setTitleColor("#333333");
        mheader.setLeftBottonIcon(R.drawable.shop_back);
        mheader.setLeftButtonOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                goBack(ShopOrderManagerActivity.class);
            }
        });
        mheader.hindRightOneButton();
        mheader.hindRightTwoButton();
        mheader.setRootBackgroundColor("#fafafa");

        //所有
        tv_order_all = (TextView) findViewById(R.id.tv_shop_order_manager_all);
        tv_order_all.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                changeTextStyle(v);
            }
        });

        tv_order_obligation = (TextView) findViewById(R.id.tv_shop_order_manager_obligation);
        tv_order_obligation.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                changeTextStyle(v);
            }
        });

        tv_order_wait = (TextView) findViewById(R.id.tv_shop_order_manager_wait);
        tv_order_wait.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                changeTextStyle(v);
            }
        });

        tv_order_over = (TextView) findViewById(R.id.tv_shop_order_manager_over);
        tv_order_over.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                changeTextStyle(v);
            }
        });

        tv_order_cancle = (TextView) findViewById(R.id.tv_shop_order_manager_cancel);
        tv_order_cancle.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                changeTextStyle(v);
            }
        });

        lv_content = (ListView) findViewById(R.id.lv_shop_order_manager_content);
        adapter = new ShopOrderManagerItemAdapter(this);
        adapter.setListener(new ShopOrderManagerItemAdapter.IButtonOnClickListener()
        {
            @Override
            public void goOrderDetail(String orderId)
            {
                managerPresenter.goShopOrderDetail(ShopOrderManagerActivity.this, orderId, ShopOrderManagerActivity.this);
            }

            @Override
            public void cancleOrder(String orderId)
            {
                managerPresenter.updateOrderStatus(orderId, 5, state);
            }

            @Override
            public void goPay(final String orderId, final int money)
            {
                UiUtils.showPayDialog(ShopOrderManagerActivity.this, money, new UiUtils.IPayListener()
                {
                    @Override
                    public void weixinPay()
                    {
                        managerPresenter.weixinpay(orderId, money);
                    }

                    @Override
                    public void ilPay()
                    {
                        managerPresenter.alipay(orderId, money);
                    }
                });
            }

            @Override
            public void returnOrder(String orderId)
            {
                //managerPresenter.updateOrderStatus(orderId, 6, state);
                com.zgm.utils.UiUtils.showDialog(ShopOrderManagerActivity.this, "退款提示", ShopOrderManagerActivity.this.getString(R.string.return_shop));
            }

            @Override
            public void confirmOrder(String orderId)
            {
                managerPresenter.updateOrderStatus(orderId, 4, state);
            }

            @Override
            public void aginBuy(String orderId)
            {

            }
        });
        lv_content.setAdapter(adapter);
        lv_content.setVisibility(View.GONE);

        ll_noram = (LinearLayout) findViewById(R.id.ll_shop_order_manager_normal);
        ll_noram.setVisibility(View.VISIBLE);

        initBarState(state);
        managerPresenter.refreshList(state);
    }

    private void changeTextStyle(View view)
    {
        tv_order_all.setTextColor(Color.parseColor("#333333"));
        tv_order_all.setBackground(null);
        tv_order_obligation.setTextColor(Color.parseColor("#333333"));
        tv_order_obligation.setBackground(null);
        tv_order_wait.setTextColor(Color.parseColor("#333333"));
        tv_order_wait.setBackground(null);
        tv_order_over.setTextColor(Color.parseColor("#333333"));
        tv_order_over.setBackground(null);
        tv_order_cancle.setTextColor(Color.parseColor("#333333"));
        tv_order_cancle.setBackground(null);

        if (tv_order_all == view)
        {
            tv_order_all.setTextColor(Color.parseColor("#ff6537"));
            tv_order_all.setBackgroundResource(R.drawable.text_bottom_border_style);
            state = 0;
            managerPresenter.refreshList(0);
        } else if (tv_order_obligation == view)
        {
            tv_order_obligation.setTextColor(Color.parseColor("#ff6537"));
            tv_order_obligation.setBackgroundResource(R.drawable.text_bottom_border_style);
            state = 1;
            managerPresenter.refreshList(1);
        } else if (tv_order_wait == view)
        {
            tv_order_wait.setTextColor(Color.parseColor("#ff6537"));
            tv_order_wait.setBackgroundResource(R.drawable.text_bottom_border_style);
            state = 3;
            managerPresenter.refreshList(3);
        } else if (tv_order_over == view)
        {
            tv_order_over.setTextColor(Color.parseColor("#ff6537"));
            tv_order_over.setBackgroundResource(R.drawable.text_bottom_border_style);
            state = 4;
            managerPresenter.refreshList(4);
        } else if (tv_order_cancle == view)
        {
            tv_order_cancle.setTextColor(Color.parseColor("#ff6537"));
            tv_order_cancle.setBackgroundResource(R.drawable.text_bottom_border_style);
            state = 5;
            managerPresenter.refreshList(5);
        }
    }

    private void initBarState(int state)
    {
        tv_order_all.setTextColor(Color.parseColor("#333333"));
        tv_order_all.setBackground(null);
        tv_order_obligation.setTextColor(Color.parseColor("#333333"));
        tv_order_obligation.setBackground(null);
        tv_order_wait.setTextColor(Color.parseColor("#333333"));
        tv_order_wait.setBackground(null);
        tv_order_over.setTextColor(Color.parseColor("#333333"));
        tv_order_over.setBackground(null);
        tv_order_cancle.setTextColor(Color.parseColor("#333333"));
        tv_order_cancle.setBackground(null);

        switch (state)
        {
            case 0:
                tv_order_all.setTextColor(Color.parseColor("#ff6537"));
                tv_order_all.setBackgroundResource(R.drawable.text_bottom_border_style);
                break;
            case 1:
                tv_order_obligation.setTextColor(Color.parseColor("#ff6537"));
                tv_order_obligation.setBackgroundResource(R.drawable.text_bottom_border_style);
                break;
            case 2:
                tv_order_wait.setTextColor(Color.parseColor("#ff6537"));
                tv_order_wait.setBackgroundResource(R.drawable.text_bottom_border_style);
                break;
            case 3:
                tv_order_over.setTextColor(Color.parseColor("#ff6537"));
                tv_order_over.setBackgroundResource(R.drawable.text_bottom_border_style);
                break;
            case 4:
                tv_order_cancle.setTextColor(Color.parseColor("#ff6537"));
                tv_order_cancle.setBackgroundResource(R.drawable.text_bottom_border_style);
                break;
        }

    }

    @Override
    protected int getLayoutResId()
    {
        return R.layout.shop_order_manager_activity;
    }

    @Override
    protected IPresenter[] getPresenters()
    {
        return new IPresenter[]{managerPresenter};
    }

    @Override
    protected void onInitPresenter()
    {
        managerPresenter.init(this, this);
    }

    @Override
    public void refreshList(List<ShopOrder> list)
    {
        if (list == null || list.size() == 0)
        {
            ll_noram.setVisibility(View.VISIBLE);
            lv_content.setVisibility(View.GONE);
        } else
        {
            ll_noram.setVisibility(View.GONE);
            lv_content.setVisibility(View.VISIBLE);
            adapter.setmList(list);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void ilPay(final String data)
    {
        Runnable payRunnable = new Runnable()
        {
            @Override
            public void run()
            {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ShopOrderManagerActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(data, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHander.sendMessage(msg);
            }
        };
        Thread thread = new Thread(payRunnable);
        thread.start();
    }

    @Override
    public void weixinPay(WeixinPayInfo payInfo)
    {
        PayReq payRequest = new PayReq();
        payRequest.appId = Config.WX_APP_ID;
        payRequest.partnerId = payInfo.getPartnerid();
        payRequest.prepayId = payInfo.getPrepayid();
        payRequest.packageValue = payInfo.getPackages();
        payRequest.nonceStr = payInfo.getNoncestr();
        payRequest.timeStamp = payInfo.getTimestamp();
        payRequest.sign = payInfo.getSign();

        boolean result = api.sendReq(payRequest);
        if (!result)
        {
            showMessage("请检查微信是否启动");
        }
    }
}
